import time

import pygame
import math
import random
import sys

from drawing import *
from ShowScore import *

# 游戏开始
from game_stats import *




def start_game(status, ai_settings, screen):
    if not status.game_active:
        # 重置游戏统计信息
        status.game_active = True
        status.suspend=False
        pygame.mixer.music.load("../resourse/music/playing_music.mp3")
        pygame.mixer.music.play()

# 检测游戏按钮被点击的情况
def check_buttonClicked(stats, ai_settings, screen, buttons, mouse_x, mouse_y,athletelst):
    play_button = buttons[0]
    s_c_button = buttons[1]
    exit_button = buttons[2]
    practice_button = buttons[3]
    simply_button = buttons[4]
    hard_button = buttons[5]

    if not stats.game_active:
        # 检测开始按钮是否被点击
        button_clicked_p = play_button.rect.collidepoint(mouse_x, mouse_y)
        if button_clicked_p:
            # 重置游戏设置
            start_game(stats, ai_settings, screen)
    else:
        button_clicked_pb = practice_button.rect.collidepoint(mouse_x, mouse_y)
        button_clicked_sb = simply_button.rect.collidepoint(mouse_x, mouse_y)
        button_clicked_hb = hard_button.rect.collidepoint(mouse_x, mouse_y)
        flag = False
        if button_clicked_pb:
            stats.practice = True
            athletelst.remove(athletelst[2])
            athletelst.remove(athletelst[2])
            # print(athletelst)

            flag = True
        elif button_clicked_sb:
            stats.simply = True
            athletelst.remove(athletelst[3])

            flag = True
            pass
        elif button_clicked_hb:
            stats.hard = True
            flag = True
            pass
        if flag:
            stats.isSelected = True

        # button_clicked_scb=s_c_button


        return athletelst

# 创建运动员
def createAthlete(screen, ai_settings,stats):
    # 颜色
    global ath
    Blue = (0, 0, 255)
    Red = (255, 0, 0)
    # 红蓝中锋
    CtB = Center(screen, ai_settings, Blue)
    CtR = Center(screen, ai_settings, Red)
    # 守门员
    gtB = goaltender(screen, ai_settings, Blue)
    gtR = goaltender(screen, ai_settings, Red)

    ldB = LDefenseman(screen, ai_settings, Blue)
    ldR = LDefenseman(screen, ai_settings, Red)

    # 右控卫
    rdB = RDefenseman(screen, ai_settings, Blue)
    rdR = RDefenseman(screen, ai_settings, Red)
    # ls_dm = [ldB, ldR, rdB, rdR]
    # 左边锋
    lwB = LWinger(screen, ai_settings, Blue)
    lwR = LWinger(screen, ai_settings, Red)
    # 右边锋
    rwB = RWinger(screen, ai_settings, Blue)
    rwR = RWinger(screen, ai_settings, Red)

    ls_ct = [CtB, CtR]
    ls_gt = [gtB, gtR]
    ls_dm = [ldB, ldR, rdB, rdR]
    ls_Wg = [lwB, lwR, rwB, rwR]
    ath = [ls_ct, ls_gt, ls_dm, ls_Wg]

    return ath

def ath2Ball(athletelst,ball):
    for i in athletelst:
        for j in i:
            j.keep=False
    ball.beKeep=False

# 确定当前控制的对象是哪一个
def check_currentControl(ai_settings, athlete_list):
    for i in athlete_list:
        for j in i:
            if j.keep:
                if j.color == (0, 0, 255) and ai_settings.currentTeam == 0:
                    return j
                else:
                    # 如果是红方接到球，则当前控制的依然是中锋
                    return athlete_list[0][0]

    else:
        # 如果当前我方无人持球，则默认当前控制对象为蓝色中锋
        return athlete_list[0][0]


# 检测碰撞
def check_Athlete_Ball_collisiongs(ai_settings, screen, cureent_control, ball):
    pos_cc = cureent_control.pos
    pos_bl = ball.pos
    juli = math.sqrt( \
        math.pow((pos_cc[0] - pos_bl[0]), 2) + \
        math.pow((pos_cc[1] - pos_bl[1]), 2))
    if juli < cureent_control.radius + ball.radius - 5:
        # 需要运动员摸到球了才算其获得球 而不是单纯碰撞才算获球
        return True
    else:
        return False


# 为了保持球在静止状态的方向，则需要设立一个Flag布尔值来确认是否发生了移动
def move(event, cureent_control, ball):
    Flag = False
    # cc_posx = cureent_control.pos[0]
    # cc_posy = cureent_control.pos[1]
    # mouse_posx = pygame.mouse.get_pos()[0]
    # mouse_posy = pygame.mouse.get_pos()[1]
    # 向右x增，向下y增
    if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
        Flag = True
        cureent_control.moving_right = True
        if cureent_control.keep == True:
            ball.dR = True

    elif event.key == pygame.K_LEFT or event.key == pygame.K_a:
        Flag = True
        cureent_control.moving_left = True
        if cureent_control.keep == True:
            ball.dL = True

    elif event.key == pygame.K_UP or event.key == pygame.K_w:
        Flag = True
        cureent_control.moving_up = True
        if cureent_control.keep == True:
            ball.dU = True

    elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
        Flag = True
        cureent_control.moving_down = True
        if cureent_control.keep == True:
            ball.dD = True
    return Flag

# 检测球的运动情况并判断守门员是否要进行移动
def checkBallToMovegt(ball, gt,stats) :
    # 获取球的位置，如果球的位置在守门员位置的上方，则守门员向上移动，直到与球在同一水平
    # 如果球的位置在守门员位置的下方，则守门员向下移动，直到与球在同一水平
    if stats.simply:
        gt.speedy = 1.2
    if stats.hard:
        gt.speedy = 2
    if gt.keep == False:
        By = ball.pos[1]
        if gt.pos[1] > By and gt.pos[1] > gt.minY:
            gt.pos[1] -= gt.speedy
        elif gt.pos[1] < By and gt.pos[1] < gt.maxY:
            gt.pos[1] += gt.speedy

#红色中锋随球移动
def checkBallToMoveCtR(ball,ct,current_control):
    if current_control !=ct:
        By = ball.pos[1]
        Bx = ball.pos[0]
        temp = random.uniform(0.1,0.8)
        if  ct.pos[0] < Bx and ct.pos[0] < ct.maxX:
            ct.pos[0] += ct.speedx+temp
        elif  ct.pos[0]>Bx and ct.pos[0] > ct.minX:
            ct.pos[0] -= ct.speedx+temp
        if ct.pos[1] <By and ct.pos[1] < ct.maxY:
            ct.pos[1] += ct.speedy+temp
        elif  ct.pos[1] >By and ct.pos[1] >ct.minY:
            ct.pos[1] -= ct.speedy+temp
# 控卫移动
def checkBallToMovedm(ball, dm,current_control):
    if  current_control != dm and dm.keep ==False:

        By = ball.pos[1]
        Bx = ball.pos[0]
        temp = random.uniform(0.1,0.8)
        # if self.flag==False:
        if  dm.pos[0] < Bx and dm.pos[0] <dm.maxX:
            # dm.move_right = True
            dm.pos[0] += dm.speedx+temp

        elif  dm.pos[0] > Bx and dm.pos[0]>dm.minX:
            # dm.move_left = True
            dm.pos[0] -= dm.speedx+temp
        if dm.pos[1] < By and dm.pos[1]<dm.maxY:
            # dm.move_up = True
            dm.pos[1] += dm.speedy+temp
        elif  dm.pos[1] > By and dm.pos[1]>dm.minY:
            # dm.move_down = True
            dm.pos[1] -= dm.speedy+temp
    # else:
    #     dm.move_right = False
    #     dm.move_left = False
    #     dm.move_up = False
    #     dm.move_down = False


def checkBallToMovewg(ball, wg, current_control):
    if current_control != wg and wg.keep == False:
        By = ball.pos[1]
        temp1 = random.uniform(0.5, 0.7)
        temp2 = random.uniform(0.1, 1)
        if  wg.pos[1] > By and wg.pos[1] > wg.minY:
            wg.pos[1] -= wg.speedy + temp1
            wg.pos[0] -= temp2
        elif wg.pos[1] < By and wg.pos[1] < wg.maxY:
            wg.pos[1] += wg.speedy + temp1
            wg.pos[0] += temp2
# 检测球与守门员的碰撞
# 只有球融入到守门员的一定范围，才判断守门员接到球了

def checkGt(ball, gt):
    pos_b = ball.pos
    pos_g = gt.pos
    juli = math.sqrt(
        math.pow(pos_b[0] - pos_g[0], 2) + \
        math.pow(pos_b[1] - pos_g[1], 2)
    )
    if juli < gt.radius + ball.radius - 5:
        # 守门员接到球，球停止运动
        ball.beKeep = True
        gt.keep = True
        return True
    else:
        return False

#检测蓝控卫是否拿到球

#检测是否碰到球
def checkTOball(ball , ld):
    pos_b = ball.pos
    pos_ld = ld.pos
    juli = math.sqrt(
        math.pow(pos_b[0] - pos_ld[0], 2) + \
        math.pow(pos_b[1] - pos_ld[1], 2)
    )
    if juli < ld.radius + ball.radius - 5:
        # 控卫接到球，球反弹运动
        ball.beKeep = True
        ld.keep = True
        return True
    else:
        return False

#检测红控卫是否碰到球



def check_keydown_event(screen, ai_settings, event, cureent_control, ball):
    if (move(event, cureent_control, ball)):
        ball.emptyStatus()


def check_keyup_event(event,stats, cureent_control):
    if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
        cureent_control.moving_right = False
    if event.key == pygame.K_LEFT or event.key == pygame.K_a:
        cureent_control.moving_left = False
    if event.key == pygame.K_UP or event.key == pygame.K_w:
        cureent_control.moving_up = False
    if event.key == pygame.K_DOWN or event.key == pygame.K_s:
        cureent_control.moving_down = False
    if event.key==pygame.K_p:
        if stats.suspend:
            pygame.mixer.music.unpause()
            stats.suspend=False
        else:
            pygame.mixer.music.unpause()
            stats.suspend=True
    if event.key==pygame.K_q:
        stats.stop=True


def check_eventes(screen, ai_settings, stats, ball, current_control, buttons,athletelst):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_event(screen, ai_settings, event, current_control, ball)
        elif event.type == pygame.KEYUP:
            check_keyup_event(event,stats, current_control)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            pygame.mixer.Sound("../resourse/music/mouse_music.mp3").play()
            if not stats.game_active or not stats.isSelected:
                mouse_x, mouse_y = pygame.mouse.get_pos()
                athletelst = check_buttonClicked(stats, ai_settings, screen, buttons, mouse_x, mouse_y,athletelst)
            else:
                if pygame.mouse.get_pressed() and stats.suspend==False:
                    # print(event.pos)
                    if current_control.keep == True:
                        current_control.keep = False
                        ball.beKeep = False
                        if ball.dU:
                            ball.speedy = -current_control.fireBall_speedy
                        elif ball.dD:
                            ball.speedy = current_control.fireBall_speedy
                        if ball.dR:
                            ball.speedx = current_control.fireBall_speedx
                        elif ball.dL:
                            ball.speedx = -current_control.fireBall_speedx
                        ath2Ball(athletelst, ball)
            x, y = pygame.mouse.get_pos()
            if 1100 <= x <= 1140 and 70 <= y <= 110 and stats.suspend==False:
                stats.suspend = True
            if 1145 <= x <= 1185 and 70 <= y <= 110:
                stats.stop = True
            if 505<=x<=705 and 255 <=y<=455 and stats.suspend==True:
                stats.suspend=False
        elif event.type==pygame.MOUSEMOTION:
            x,y=pygame.mouse.get_pos()
            if stats.suspend or not stats.game_active or not stats.isSelected or (1100<=x<=1185 and 70<=y<=110):
                pygame.mouse.set_visible(True)
            else:
                pygame.mouse.set_visible(False)

# 检查是否红方AI控制到球了
def checkWhoKeepBall(athlete_list, ball,stats):
    gtR = athlete_list[1][1]
    ctR = athlete_list[0][1]
    gtR.speedx = 1
    gtR.speedy = 1
    ctR.speedx = 0.5
    ctR.speedy = 0.5
    if gtR.keep:
        ball.speedx = -gtR.fireBall_speedx

        ball.beKeep = False
        gtR.keep = False

    if stats.simply :
        dmR1 = athlete_list[2][1]
        dmR2 = athlete_list[2][3]

        if gtR.keep:
            ball.speedx = -gtR.fireBall_speedx

            ball.beKeep = False
            gtR.keep = False
        elif ctR.keep:
            ball.speedx = -ctR.fireBall_speedx
            ball.speedy = -ctR.fireBall_speedy
            ball.beKeep = False
            ctR.keep = False
        elif dmR2.keep:
            ball.speedx = -dmR2.fireBall_speedx
            ball.speedt = -dmR2.fireBall_speedy
            dmR2.speedx = 1.2
            dmR2.speedx = 1.2
            ball.beKeep = False
            dmR2.keep = False
        elif dmR1.keep:
            ball.speedx = -dmR1.fireBall_speedx
            ball.speedy = -dmR1.fireBall_speedy
            dmR1.speedx = 1.1
            dmR1.speedy = 1.1
            ball.beKeep = False
            dmR1.keep = False
    elif stats.hard:
        dmR1 = athlete_list[2][1]
        dmR2 = athlete_list[2][3]
        wgR1 = athlete_list[3][1]
        wgR2 = athlete_list[3][3]
        if gtR.keep:
            ball.speedx = -gtR.fireBall_speedx

            ball.beKeep = False
            gtR.keep = False
        elif ctR.keep:
            ball.speedx = -ctR.fireBall_speedx
            ball.speedy = -ctR.fireBall_speedy
            ball.beKeep = False
            ctR.keep = False

        elif dmR2.keep:
            ball.speedx = -dmR2.fireBall_speedx
            ball.speedt = -dmR2.fireBall_speedy
            dmR2.speedx = 1.2
            dmR2.speedx = 1.2
            ball.beKeep = False
            dmR2.keep = False
        elif dmR1.keep:
            ball.speedx = -dmR1.fireBall_speedx
            ball.speedy = -dmR1.fireBall_speedy
            dmR1.speedx = 1.1
            dmR1.speedy = 1.1
            ball.beKeep = False
            dmR1.keep = False

        elif wgR1.keep:
            ball.speedx = -wgR1.fireBall_speedx
            ball.speedy = -wgR1.fireBall_speedy
            wgR1.speedx = 1.3
            wgR1.speedy = 1.3
            ball.beKeep = False
            wgR1.keep = False
        elif wgR2.keep:
            wgR2.speedx = 1.2
            wgR2.speedy = 1.2
            ball.speedx = -wgR2.fireBall_speedx
            ball.speedy = -wgR2.fireBall_speedy
            ball.beKeep = False
            wgR2.keep = False


def checkcollide(group,current_control):
    flag = False

    for each in group:
        group.remove(each)
        pos_each = each.pos
        for othereach in group:
            pos_othereach = othereach.pos
            juli = math.sqrt(math.pow((pos_each[0] - pos_othereach[0]), 2) + math.pow((pos_each[1] - pos_othereach[1]), 2))
            if juli  < 20 and each != current_control:
                # print('太近了！')
                each.pos[0] = each.pos[0]-random.randint(2,5)
                each.pos[1] = each.pos[1] +random.randint(2,5)
                flag = True

    group.add(each)
    return flag

# Restore all positions of the athlete
def restoreAth(athlst):
    for ath in athlst:
        for a in ath:
            a.restore()

# 更新屏幕
def update_screen(screen, ai_settings, stats, ball, athlete_list, buttons, showscore,current_control):
    play_button = buttons[0]
    s_c_button = buttons[1]
    stop_button = buttons[2]
    practice_button = buttons[3]
    simply_button = buttons[4]
    hard_button = buttons[5]

    if stats.suspend==False:
        current_control = check_currentControl(ai_settings, athlete_list)

        # 判断当前控制的运动员是否有接到球
        if check_Athlete_Ball_collisiongs(ai_settings, screen, current_control, ball):
            current_control.keep = True
            ball.beKeep = True

        # 中锋
        CtLst = athlete_list[0]

        gtLst = athlete_list[1]
        group = pygame.sprite.Group()
        group.add(CtLst[0])
        group.add(CtLst[1])
        if stats.simply:
            dmbLst =[athlete_list[2][0],athlete_list[2][2]]
            dmrLst =[athlete_list[2][1],athlete_list[2][3]]
            group.add(dmbLst[0])
            group.add(dmbLst[1])
            group.add(dmrLst[0])
            group.add(dmrLst[1])
        elif stats.hard:
            dmbLst = [athlete_list[2][0], athlete_list[2][2]]
            dmrLst = [athlete_list[2][1], athlete_list[2][3]]
            wgbLst = [athlete_list[3][0],athlete_list[3][2]]

            wgrLst = [athlete_list[3][1],athlete_list[3][3]]
            group.add(dmbLst[0])
            group.add(dmbLst[1])
            group.add(dmrLst[0])
            group.add(dmrLst[1])
            group.add(wgbLst[0])
            group.add(wgbLst[1])
            group.add(wgrLst[0])
            group.add(wgrLst[1])

        # balls = [CtLst[0],CtLst[1],dmLst[0],dmLst[1],dmLst[2],dmLst[3],lwLst[0],lwLst[1],lwLst[2],lwLst[3]]
        # group = pygame.sprite.Group()
        # group.add(CtLst[0])
        # group.add(CtLst[1])
        # group.add(dmbLst[0])
        # group.add(dmbLst[1])
        # group.add(dmrLst[0])
        # group.add(dmrLst[1])
        # group.add(wgbLst[0])
        # group.add(wgbLst[1])
        # group.add(wgrLst[0])
        # group.add(wgrLst[1])
        #
        # for each in group:
        #     group.remove(each)
        #     if pygame.sprite.spritecollide(each,group,False, pygame.sprite.collide_circle):
        #
        #         if each!=current_control:
        #             pass
        #             # print('123')
        #             # print(each.pos)
        #             # each.speedx = -each.speedx
        #             # each.speedy = -each.speedy
        #     else:
        #         pass
        #
        #     group.add(each)

        for gt in gtLst:
            if checkGt(ball, gt):
                break

        #蓝方拿球控球
        if stats.simply or stats.hard:
            if checkTOball(ball, dmbLst[0]):
                current_control = dmbLst[0]

            elif checkTOball(ball, dmbLst[1]):
                current_control = dmbLst[1]

            elif stats.hard:
                if checkTOball(ball, wgbLst[0]):
                    current_control = wgbLst[0]

                elif checkTOball(ball, wgbLst[1]):
                    current_control = wgbLst[1]
            # 红方拿球反弹
            if checkTOball(ball, CtLst[1]):
                pass


            elif checkTOball(ball, dmrLst[0]):
                pass

            elif checkTOball(ball,dmrLst[1]):
                pass

            if stats.hard:

                if checkTOball(ball, wgrLst[0]):
                    pass

                elif checkTOball(ball, wgrLst[1]):
                    pass


        if ball.ShootGoal():
            if ball.pos[0] > 1068:
                # 蓝队胜
                ball.pos[0] = 1080
                ball.pos[1] = 343
                print("Blue Win!")
                GameStats.scoreBule +=10   #由于获取数使用round（）第二个参数为负数，将圆整到最近的10、100、1000等整数倍。 所以score值必须大于10 才能显示更新
                print("bule " + str(showscore.stats.scoreBule))
                pygame.mixer.Sound("../resourse/music/whistling.mp3").play()
                time.sleep(2)
                ball.pos = [600.5, 340]
            else:
                # 红队胜
                ball.pos[0] = 121
                ball.pos[1] = 343
                print("Red Win!")
                GameStats.scoreRed += 10  # 由于获取数使用round（）第二个参数为负数，将圆整到最近的10、100、1000等整数倍。 所以score值必须大于10 才能显示更新
                print("red " + str(showscore.stats.scoreRed))
                pygame.mixer.Sound("../resourse/music/whistling.mp3").play()
                time.sleep(2)
                ball.pos = [600.5, 340]
            restoreAth(athlete_list)
            ball.speedx = 0
            ball.speedy = 0

        # 守门员(左右控卫)根据球的运动情况进行移动
        for i in range(len(gtLst)):
            checkBallToMovegt(ball, gtLst[i],stats)

        if stats.simply or stats.hard:
            #如果球距离太近就不随着球运动
            if checkcollide(group,current_control):
                pass
            else:
                # 红中锋根据球的运动情况运动
                checkBallToMoveCtR(ball, CtLst[1], current_control)
                checkBallToMoveCtR(ball, CtLst[0], current_control)
        if stats.simply or stats.hard:
            if checkcollide(group,current_control):
                pass
            else:
                for i in range(len(dmrLst)):
                    checkBallToMovedm(ball, dmrLst[i], current_control)

                for i in range(len(dmbLst)):
                    checkBallToMovedm(ball, dmbLst[i], current_control)
                    if stats.hard:
                        for i in range(len(wgbLst)):
                            checkBallToMovewg(ball,wgbLst[i],current_control)
                        for i in range(len(wgrLst)):
                            checkBallToMovewg(ball,wgrLst[i],current_control)

        checkWhoKeepBall(athlete_list, ball,stats)
        current_control.update()
        ball.update()
    screen.fill(ai_settings.bg_color)

    # 绘制场地
    drawScene(screen, ai_settings)
    #显示分数，在屏幕背景绘制之后
    showscore.show_score()

    if stats.suspend==False:
        # 绘制运动员
        drawAthlete(screen, ai_settings, stats, current_control, athlete_list)
        # 绘制球
        drawBall(screen, current_control, ball)



    # 绘制游戏开始按钮
    if not stats.game_active:
        play_button.draw_button()
    else:
        if not stats.isSelected:
            practice_button.draw_button()
            simply_button.draw_button()
            hard_button.draw_button()
        else:
            sb = "../resourse/pic/suspend.png"
            cb = "../resourse/pic/continue.png"

            img=sb
            transformSize=(40,40)
            imgPos=[1100,70]
            if stats.suspend:
                img=cb
                transformSize=(200,200)
                imgPos=[505,255]
            else:
                img = sb
                transformSize = (40, 40)
                imgPos = [1100, 70]
            s_c_button.blitButton(screen,img,transformSize,imgPos)

            stop_button.blitButton(screen,"../resourse/pic/stop.png",(40,40),[1145,70])


    # 更新页面
    pygame.display.flip()

    if stats.suspend==False:
        # 返回最新获得的当前控制运动员
        return current_control
    else:
        return None
